package com.yc.configs;

import com.alibaba.druid.pool.DruidDataSource;
import com.sun.xml.internal.ws.api.FeatureListValidatorAnnotation;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import javax.sql.DataSource;

/**
 * @ClassName DataSourceConfig
 * @since: 2023/8/2 15:05
 * @auth: kirito
 * @description:
 **/
@Configuration
@PropertySource("classpath:db.properties")
@Data  //lom book创建get set
@Log4j2
public class DataSourceConfig {

    //利用DI注入db.properties
    @Value("${mysql.driverclass}")
    private String driverclass;
    @Value("${mysql.user}")
    private String user;
    @Value("${mysql.password}")
    private String password;
    @Value("${mysql.url}")
    private String url;

    @Value("#{T(Runtime).getRuntime().availableProcessors()*2}")
    //spEl-> spring expression language
    private int cpuCount;

    //以上属性从db.properties读取出来  存到了spring容器的 Environment变量中  系统环境变量也在这

    @Bean(initMethod = "init", destroyMethod = "close") //DruidDataSource提供了init初始化方法
    public DruidDataSource druidDataSource() {      //另外要注意：idea会对这个方法返回值进行解析，判断是否有init
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverclass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        //以上只是配置了参数 没有创建连接池  在这个类的init中完成了连接池创建
        //当前主机的CPU*2
//        (Runtime).getRuntime().availableProcessors()*2
        log.info("配置druid的连接池大小：" + cpuCount);
        dataSource.setInitialSize(cpuCount);
        dataSource.setMaxActive(cpuCount*2);
        //todo：更多参数
        return dataSource;
    }
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(driverclass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        //todo：更多参数
        return dataSource;
    }

    @Bean
    public DataSource dbcpDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driverclass);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        //todo：更多参数
        return dataSource;
    }

}
